/**
 * 楼盘详情
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var util = require("util");
    var ui = require("ui");
    var tmpl = require("tmpl");
    require("uploader");
    var api_prefix = G_CONFIG["api_prefix"] + "/qmyx/building-info/"; //api前缀
    var buidingSetting = require("./building_setting");

    var BuildingDetail = {
        init: function() {
            this.bindEvent();
            if(buidingSetting.proj_id){
                this.getBuildingStatus();
                this.getBrokerAndCstCount();
            }
            this.isOnline = true;
            this.initForm();
            buidingSetting.checkDataModify = $.proxy(this.checkDataModify,this);
        },
        editorMap: {},
        getBuildingStatus:function(){
            util.getParamValuesByCode("brokerStatus",buidingSetting.proj_id,function(data){
                var types = [];
                $.each(data,function(i,item){
                    types.push({text:item.Text,value:item.Value});
                });
                var cfg = {
                    id:"ddl_status",
                    list:types
                };
                if(buidingSetting.building_data){
                    cfg.defValue = buidingSetting.building_data.status;
                }
                $.select(cfg);
            },this);
        },
        getBrokerAndCstCount:function(){
            var data = {
                proj_id:buidingSetting.proj_id
            };
            var url = api_prefix + "get-partner-broker-and-intention-cst-count";
            util.myAjax({
                url: url,
                type: "get",
                data:data,
                context: this,
                success: function(json) {
                    if (json.retCode == 0) {
                        var broker_count = json.data.partnerBrokerCount || 0;
                        var intent_cst_count = json.data.intentionCstCount || 0;
                        $("#broker_count").text(broker_count);
                        $("#intent_cst_count").text(intent_cst_count);
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                }
            });
        },
        initForm:function(){
            var data = buidingSetting.building_data;
            if(data){
                $("#building_name").val(data.lp_name);
                if(data.lp_pic){
                    $("#img_wrap").html('<img src="' + data.lp_pic + '" alt="" /> ');
                    $("#building_img").val(data.lp_pic);
                }
                $("#admin_tel").val(data.service_admin_tel);
                $("#commission_info").val(data.CommissionInfo);
                $("#excitation_info").val(data.ExcitationInfo);
                $("#price").val(data.price);
                $("#address").val(data.address);
                $("#longitude").val(data.longitude);
                $("#latitude").val(data.latitude);
                if(data.end_date){
                    var dt = new Date();
                    var now = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate());
                    if(now >= util.parseDate(data.end_date)){
                        $("#rbt_offline").prop("checked",true);
                        this.isOnline = false;
                    }else{
                        $("#rbt_online").prop("checked",true);
                        this.isOnline = true;
                    }
                }
                if(data.IsVisibleBuilding == "0"){
                    ui.offSwitch("new_building");
                }
                if(data.IsDisplayBroker == '1'){
                    ui.openSwitch("display_broker");
                }
                if(data.IsDisplayCst == '1'){
                    ui.openSwitch("intent_cst");
                }
            }
            this.initEditor("ed_cooperation_rules",data ? data.cooperation_rules : "");
            this.initEditor("ed_preferential",data ? data.preferential : "");
            this.initEditor("ed_selling_points",data ? data.selling_points : "");
            this.initEditor("ed_target_customer",data ? data.target_customer : "");
            this.initEditor("ed_talk_skills",data ? data.talk_skills : "");
            this.initEditor("ed_support",data ? data.support : "");
        },
        initEditor:function(container,value){
            var editor = this.editorMap[container];

            if(editor){
                try {
                    editor.destroy();
                } catch (e) {
                    //nothing
                }
                this.editorMap[container] = null;
            }

            editor = UM.createEditor(container);
            editor.ready(function () {
                if (value) {
                    editor.setContent(value);
                    editor.oldContentTxt = editor.getContentTxt();
                } else {
                    editor.oldContentTxt = "";
                }
            });

            this.editorMap[container] = editor;
        },
        //校验
        checkFormData:function(){
            if(!buidingSetting.proj_id){
                ui.showErrTip("请先选择项目");
                return false;
            }
            var lp_name = ui.checkField("building_name",true);
            var lp_pic = ui.checkField("building_img",true);
            var admin_tel = ui.checkField("admin_tel",true);
            var status = ui.checkDropDownList("ddl_status",true);
            var address = ui.checkField("address",true);
            
            if(lp_name === false || lp_pic === false
                || admin_tel === false || status === false || address === false){
                return false;
            }
            var end_date = this.getEndDate();
            var longitude = ui.checkField("longitude",false);
            var latitude = ui.checkField("latitude",false);
            var commission_info = ui.checkField("commission_info",false);
            var excitation_info = ui.checkField("excitation_info",false);
            var price = ui.checkField("price",false);
            var new_building = $("#new_building").hasClass("switch-on") ? "1" : "0";
            var display_broker = $("#display_broker").hasClass("switch-on") ? "1" : "0";
            var intent_cst = $("#intent_cst").hasClass("switch-on") ? "1" : "0";

            var editorMap = this.editorMap;
            var cooperation_rules = editorMap["ed_cooperation_rules"].getContent();
            var preferential = editorMap["ed_preferential"].getContent();
            var selling_points = editorMap["ed_selling_points"].getContent();
            var target_customer = editorMap["ed_target_customer"].getContent();
            var talk_skills = editorMap["ed_talk_skills"].getContent();
            var support = editorMap["ed_support"].getContent();
            
            var data = {
                proj_id:buidingSetting.proj_id,
                lp_name:lp_name,
                lp_pic:lp_pic,
                end_date:end_date,
                service_admin_tel:admin_tel,
                status:status,
                address:address,
                longitude:longitude,
                latitude:latitude,
                cooperation_rules:cooperation_rules,
                preferential:preferential,
                selling_points:selling_points,
                target_customer:target_customer,
                talk_skills:talk_skills,
                support:support,
                CommissionInfo:commission_info,
                ExcitationInfo:excitation_info,
                price:price,
                IsVisibleBuilding:new_building,
                IsDisplayBroker:display_broker,
                IsDisplayCst:intent_cst
            };
            if(buidingSetting.building_id){
                data.b_regbroker_building_infoId = buidingSetting.building_id;
            }
            return data;
        },
        getEndDate:function(){
            var end_date;
            if($("#rbt_online").prop("checked")){ //上架
                end_date = "2038-12-31 00:00:00";
            }else{ //下架将时间设置为当天减1天
                var dt = new Date();
                dt.setDate(dt.getDate() - 1);
                end_date = util.formatDate(dt,"yyyy-MM-dd 00:00:00");
            }
            return end_date;
        },
        //保存
        save:function(){
            var data = this.checkFormData();
            if(!data){
                return;
            }
            var url = api_prefix + "write-building-info";
            util.myAjax({
                url: url,
                type: "POST",
                data:data,
                context: this,
                success: function(json) {
                    if (json.retCode == 0) {
                        ui.showSucTip();
                        buidingSetting.getBuildingInfo(false);
                    } else {
                        ui.showErrTip(json.errMsg);
                    }
                }
            });
        },
        //检测数据是否已修改
        checkDataModify:function(){
            try{
                if(buidingSetting.curUrl.indexOf("building_detail") == -1){
                    return false;
                }
                var data = {
                    lp_name:$("#building_name").val(),
                    lp_pic:$("#building_img").val(),
                    service_admin_tel:$("#admin_tel").val(),
                    status:ui.checkDropDownList("ddl_status",false),
                    address:$("#address").val(),
                    longitude:$("#longitude").val(),
                    latitude:$("#latitude").val(),
                    CommissionInfo:$("#commission_info").val(),
                    ExcitationInfo:$("#excitation_info").val(),
                    price:$("#price").val(),
                    IsVisibleBuilding:$("#new_building").hasClass("switch-on") ? "1" : "0",
                    IsDisplayBroker:$("#display_broker").hasClass("switch-on") ? "1" : "0",
                    IsDisplayCst:$("#intent_cst").hasClass("switch-on") ? "1" : "0"
                };

                var isModify = false;
                if(buidingSetting.building_data){
                    var org_data = buidingSetting.building_data;
                    for(var key in data){
                        if(data.hasOwnProperty(key)){
                            var value = (org_data[key] === null || org_data[key] === undefined) ? "" :org_data[key];
                            if(data[key] != value){
                                //console.log("key:" + key + ", data[key]=" + data[key] + ", org_data[key]=" + org_data[key]);
                                return true;
                            }
                        }
                    }
                    isModify = this.checkEditorContentChanged();
                }else{
                    //设置默认值
                    var org_data = {
                        IsVisibleBuilding:"1",
                        IsDisplayBroker:"0",
                        IsDisplayCst:"0"
                    };
                    for(var key in data){
                        if(data.hasOwnProperty(key)){
                            var value = (org_data[key] === null || org_data[key] === undefined) ? "" :org_data[key];
                            if(data[key] != value){
                                //console.log("key:" + key + ", data[key]=" + data[key] + ", org_data[key]=" + org_data[key]);
                                return true;
                            }
                        }
                    }
                }
                //上下架状态
                if((this.isOnline && $("#rbt_online").prop("checked") == false) || (!this.isOnline && $("#rbt_offline").prop("checked") == false)){
                    isModify = true;
                }
                return isModify;
            }catch(ex){
                return false;
            }
        },
        checkEditorContentChanged:function(){
            var arr = ["ed_cooperation_rules","ed_preferential","ed_selling_points","ed_target_customer","ed_talk_skills","ed_support"];
            var isModify = false;

            var editorMap = this.editorMap;
            $.each(arr,function(i,id){
                var editor = editorMap[id];
                if(editor && editor.getContentTxt() != editor.oldContentTxt){
                    isModify = true;
                    return false;
                }
            });
            return isModify;
        },
        bindEvent: function() {
            var _this = this;
            $("#btn_save").on("click", function(e) {
                e.preventDefault();
                _this.save();
            });
            $('#fileupload').fileupload({
                dataType: 'json',
                url:G_CONFIG["api_prefix"] + "common/file/upload-image",
                add:function(e,data){
                    if(util.checkIsImagFile(data.files[0])){
                        data.submit();
                        $("#img_wrap").append('<div class="upload-process">上传中...</div>');
                    }else{
                        $("#fileupload").nextAll(".js-err").html("请选择图片文件(jpg|jpeg|png)").show();
                    }
                },
                done: function (e, data) {
                    $("#img_wrap").find(".upload-process").remove();
                    var res = data.result;
                    $("#img_wrap").find(".upload-process").remove();
                    if(res.retCode == "0"){
                        var img_url = res.data.path;
                        $("#img_wrap").html('<img src="' + img_url + '" />');
                        $("#building_img").val(img_url);
                        $("#fileupload").nextAll(".js-err").html("");
                    }else{
                        $("#fileupload").nextAll(".js-err").html("上传失败:" + res.errMsg).show();
                    }
                }
            });
            ui.initSwitch("#new_building,#display_broker,#intent_cst");
            $("#sel_location").on("click",function(e){
                e.preventDefault();
                ui.selLocation(function(data){
                    $("#latitude").val(data.latitude);
                    $("#longitude").val(data.longitude);
                },{latitude:$("#latitude").val(),longitude:$("#longitude").val()});
            });
            ui.tab("tabEditor","tabSmCon","tab-sm-on");
        }
    };
    module.exports = BuildingDetail;
});